<template>
  <div>
    <el-card>
      <el-row :gutter="20">
        <el-col :span="18">
          <el-row :gutter="20">
            <el-col :span="8">
              <el-input
                v-model="queryInfo.username"
                placeholder="根据用户名搜索"
                clearable
                @clear="getUserList"
              ></el-input>
            </el-col>
            <el-col :span="6">
              <el-button
                class="btn"
                size="small"
                type="primary"
                plain
                @click="getUserList"
                >搜索</el-button
              >
            </el-col>
          </el-row>
        </el-col>
        <el-col :span="6">
          <el-button
            class="users"
            type="success"
            icon="el-icon-edit"
            @click="addDialogVisible = true"
            >新增用户</el-button
          >
        </el-col>
      </el-row>
      <el-alert :title="countstext" type="info" show-icon> </el-alert>
      <!-- 表格 -->
      <el-table :data="usersList" stripe style="width: 100%">
        <el-table-column type="index" label="#" width="100"> </el-table-column>
        <el-table-column prop="email" label="邮箱" width="100">
        </el-table-column>
        <el-table-column prop="phone" label="联系电话"> </el-table-column>
        <el-table-column prop="username" label="用户名"> </el-table-column>
        <el-table-column prop="permission_group_title" label="角色组名称">
        </el-table-column>
        <el-table-column prop="role" label="`角色"> </el-table-column>
        <el-table-column align="right" label="操作">
          <template slot-scope="scope">
            <!-- 编辑按钮 -->
            <el-button
              plain
              circle
              type="primary"
              icon="el-icon-edit"
              @click="showEditDialog(scope.row)"
            ></el-button>
            <!-- 删除按钮 -->
            <el-button
              plain
              circle
              type="danger"
              icon="el-icon-delete"
              @click="removeUser(scope.row)"
            ></el-button>
          </template>
        </el-table-column>
      </el-table>
      <!-- 分页 -->
      <el-pagination
        style="text-align: right; margin-top: 20px"
        background
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
        :current-page="queryInfo.page"
        :page-sizes="[1, 2, 3, 10]"
        :page-size="queryInfo.pagesize"
        layout="total,prev, pager, next, sizes,  jumper"
        :total="counts"
      >
      </el-pagination>
    </el-card>

    <!-- 添加对话框 -->
    <el-dialog
      title="创建用户"
      :visible.sync="addDialogVisible"
      width="50%"
      @close="resetAddDialog"
    >
      <el-form
        ref="addFormRef"
        label-width="80px"
        :rules="addFormRules"
        :model="addForm"
        style="width: 400px; margin-left: 120px"
      >
        <el-form-item label="用户名" prop="username">
          <el-input v-model="addForm.username"></el-input>
        </el-form-item>
        <el-form-item label="邮箱" prop="email">
          <el-input v-model="addForm.email"></el-input>
        </el-form-item>
        <el-form-item label="密码" prop="password">
          <el-input v-model="addForm.password" type="password"></el-input>
        </el-form-item>
        <el-form-item label="角色">
          <el-input v-model="addForm.role"></el-input>
        </el-form-item>
        <el-form-item label="角色组名称">
          <el-select v-model="addForm.permission_group_id" placeholder="请选择">
            <el-option
              v-for="item in options"
              :key="item.id"
              :label="item.title"
              :value="item.id"
            >
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="联系电话">
          <el-input v-model="addForm.mobile"></el-input>
        </el-form-item>
        <el-form-item label="介绍">
          <el-input
            type="textarea"
            :rows="2"
            placeholder="请输入内容"
            v-model="addForm.introduction"
          >
          </el-input>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="addDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="addUser">确 定</el-button>
      </span>
    </el-dialog>
    <!-- 修改编辑 -->
    <el-dialog title="编辑用户" :visible.sync="editDialogVisible" width="50%">
      <el-form
        ref="addFormRef"
        :model="editForm"
        :rules="addFormRules"
        label-width="120px"
        style="width: 400px; margin-left: 120px"
      >
        <el-form-item label="用户名" prop="username">
          <el-input v-model="editForm.username" disabled></el-input>
        </el-form-item>
        <el-form-item label="邮箱" prop="email">
          <el-input v-model="editForm.email"></el-input>
        </el-form-item>

        <el-form-item label="角色">
          <el-input v-model="editForm.role"></el-input>
        </el-form-item>
        <el-form-item label="权限组名称">
          <el-select
            v-model="editForm.permission_group_id"
            placeholder="请选择"
          >
            <el-option
              v-for="item in options"
              :key="item.id"
              :label="item.title"
              :value="item.id"
            >
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="联系电话">
          <el-input v-model="editForm.mobile"></el-input>
        </el-form-item>
        <el-form-item label="介绍">
          <el-input
            type="textarea"
            :rows="2"
            placeholder="请输入内容 "
            v-model="editForm.introduction"
          >
          </el-input>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="editDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="saveEditForm">确 定</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
export default {
  name: 'users',
  data () {
    var checkMobile = function (rule, value, cb) {
      var reg = /^1(3[0-9]|4[5,7]|5[0,1,2,3,5,6,7,8,9]|6[2,5,6,7]|7[0,1,7,8]|8[0-9]|9[1,8,9])\d{8}$/
      if (reg.test(value)) {
        cb()
      } else {
        cb(new Error('手机号格式不对的'))
      }
    }
    return {
      queryInfo: {
        page: 1,
        pagesize: 2,
        keyword: '',
        disabled: 0
      },
      usersList: [],
      counts: 0,
      pagesize: '',
      pages: 1,
      page: '',
      countstext: '',
      addDialogVisible: false,
      addForm: {
        username: '',
        email: '',
        password: '',
        role: '',
        permission_group_id: '',
        mobile: '',
        introduction: ''
      },
      addFormRules: {
        username: [
          { required: true, message: '请输入用户名', trigger: 'blur' },
          {
            min: 3,
            max: 10,
            message: '长度在 3 到 10 个字符',
            trigger: 'blur'
          }
        ],
        password: [
          { required: true, message: '请输入密码', trigger: 'blur' },
          {
            min: 6,
            max: 15,
            message: '长度在 6 到 15 个字符',
            trigger: 'blur'
          }
        ],
        email: [{ required: true, message: '请输入邮箱', trigger: 'blur' }],
        mobile: [
          { required: true, message: '请输入手机号', trigger: 'blur' },
          { validator: checkMobile, trigger: 'blur' }
        ]
      },
      selectedRoleId: '',
      editDialogVisible: false,
      editForm: {},
      options: []
    }
  },
  created () {
    this.getUserList()
    this.getPermission()
  },
  methods: {
    async getUserList () {
      const { data: res } = await this.$http.get('users', {
        params: this.queryInfo
      })
      console.log(res)
      this.usersList = res.list
      this.counts = res.counts
      this.countstext = `共${this.counts}条数据 注意：admin管理员不能删除，否则后台会报错`
    },
    async getPermission () {
      // 获取权限数据
      const { data: res } = await this.$http.get('permissions', {
        params: this.queryParameter
      })
      this.options = res.list
    },
    handleSizeChange (item) {
      this.queryInfo.pagesize = item
      this.getUserList()
    },
    handleCurrentChange (val) {
      this.queryInfo.page = val
      this.getUserList()
    },
    resetAddDialog () {
      this.$refs.addFormRef.resetFields()
    },
    addUser () {
      // 表单添加校验
      this.$refs.addFormRef.validate(async (valid) => {
        // 验证不通过
        if (!valid) return
        // 验证通过
        await this.$http.post('users', {
          username: this.addForm.username,
          email: this.addForm.email,
          password: this.addForm.password,
          role: this.addForm.role,
          permission_group_id: this.addForm.permission_group_id,
          phone: this.addForm.mobile,
          introduction: this.addForm.introduction
        })
        // 更新视图
        this.$message.success('新增用户成功!')
        this.getUserList()
      })

      // 关闭弹框
      this.addDialogVisible = false
    },
    async showEditDialog (row) {
      const { data } = await this.$http.get(`users/${row.id}`)
      this.editForm = data
      this.editDialogVisible = true
    },
    resetEditForm () {
      this.$refs.editFormRef.resetFields()
    },
    async saveEditForm () {
      // 表单编辑校验
      await this.$http.put(`users/${this.editForm.id}`, this.editForm)
      // 更新视图
      this.getUserList()
      this.$message.success('更新用户成功!')
      // 关闭弹窗
      this.editDialogVisible = false
    },
    removeUser (row) {
      // 删除校验
      this.$confirm('此操作将永久删除该用户, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      })
        .then(async () => {
          const { data: res } = await this.$http.delete(`users/${row}`)
          // if (res.meta.status !== 200) return this.$message.error('删除失败')
          console.log(res)
          this.$http.delete(`users/${row.id}`)
          this.getUserList()
          this.editDialogVisible = false
          this.$message.success('删除用户成功')
        })
        .catch(() => {
          this.$message({
            type: 'info',
            message: '已取消删除'
          })
        })
    }
  }
}
</script>

<style scoped lang="less">
.el-alert {
  margin: 20px 0;
}
.dialog-footer {
  display: block;
  text-align: center;
}

.el-input__inner {
  margin-bottom: 22px;
}
.btn {
  height: 36px;
}
.users {
  float: right;
}
</style>
